package com.block.datapush.service.filter;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.block.common.service.LogFactory;
import com.block.datapush.model.param.FilterHandlerParam;
import com.block.datapush.model.result.FilterHandlerResult;
import com.block.datapush.service.IDataFilterItemService;
import com.block.db.entity.MemberSourceInfo;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class FilterCityHandlerService implements IDataFilterItemService {

    private static final String ALL_CITY = "999999";

    @Override
    public FilterHandlerResult handlerFilterLogic(FilterHandlerParam handlerParam, MemberSourceInfo memberSourceInfo) {

        String userProvince = memberSourceInfo.getProvinceCode();
        String userCity = memberSourceInfo.getCityCode();

        String inCityArray = handlerParam.getInCityArray();
        String outCityArray = handlerParam.getOutCityArray();

        if (StrUtil.isEmpty(inCityArray)){
            throw new RuntimeException("机构推送城市没有选择");
        }

        List<String> inCityList = JSON.parseArray(inCityArray, String.class);
        List<String> outCityList = new ArrayList<>();
        if (StrUtil.isNotEmpty(outCityArray)){
            outCityList = JSON.parseArray(outCityArray, String.class);
        }

        if (inCityList.contains(ALL_CITY) ||
                inCityList.contains(userProvince) ||
                inCityList.contains(userCity)){
            // 包含的城市通过了
            if (CollUtil.isEmpty(outCityList)){
                return FilterHandlerResult.success();
            }

            if (!outCityList.contains(userProvince) && !outCityList.contains(userCity)){
                // 并且用户的城市不在屏蔽的范围内
                return FilterHandlerResult.success();
            }
        }

        String message = StrUtil.format("【filterIn】{}【filterOut】{}【province】{}【city】{}",
                inCityArray, outCityArray, userProvince, userCity);
        return FilterHandlerResult.error("CITY_ERROR", message);
    }
}
